(function () {
    var paper,
        midObj = {},
        winHt,
        winWt,
        legendWt = 120,
        progressTimeHandle,
        timeHandle,
        loopTimeSpan = 15000,
        //loopTimeSpan = 1000,
        svgTableDict = {},
        toolCounterDict,
        lineRateCache = {},
        todayTotalVal = 0,
        todayPlanedVal = 0,
        $stageLayer = $('#stageLayer');
    var titleBarHt = midObj.titleBarHt = 30,
        isFullScreen = false;

    var url = location.href;
    var ptn = new RegExp('.*?[\\?&]line=(\\d).*');
    var matchs = url.match(ptn);
    var lineNum;
    if (matchs && matchs.length === 2) {
        lineNum = matchs[1];
    }
    var iWh, iWw, fwh;
    var tableStrFontsize = 16;
    var tableStrFontsizeSmall = 14;
    var tableFontsize = 20;
    $(function () {
        var $win = $(window);
        iWw = $win.width();
        iWh = $win.height();
        winHt = iWh - 6;
        winWt = iWw;
        fwh = parseFloat(iWw / iWh);
        if(fwh < 1.8) {
            isFullScreen = true;
        }
        if(iWw >= 1920) {
            tableFontsize = 30;
            tableStrFontsize = 24;
            tableStrFontsizeSmall = 14;
        }
        showClock();
        initLayout();
    });
    var legDict = {
        'production end': {color: '#000'},
        'cleaning scheduled': {color: '#ddd9c4', text: ['cleaning', 'scheduled']},
        'maintanance scheduled': {color: '#a6a6a6', text: ['maintanance', 'scheduled']},
        'sample production': {color: '#006600', text: ['sample', 'production']},
        'testproduction': {color: '#009900'},
        'cooling water error': {color: '#8db4e2', text: ['cooling', 'water error']},
        'cooling air error': {color: '#e6b8b7', text: ['cooling', 'air error']},
        'heating error': {color: '#60497a'},
        'manpower shortage': {color: '#963634', text: ['manpower', 'shortage']},
        'thermo error': {color: '#632523'},
        'error production': {color: '#a50021'},
        'error maintenance': {color: '#cc0066', text: ['error', 'maintenance']},
        'error tool shop': {color: '#ff3300'},
        'error dosing furnace': {color: '#9900cc', text: ['error dosing', 'furnace']},
        'core shortage': {color: '#cc99ff'},
        'conveyor': {color: '#ffff00'},
        'furnace filling / change': {color: '#0000ff', text: ['furnace filling', '/ change']},
        'production': {color: '#00ff00'},
        'system failure': {color: '#ff0000'},
        'pressure error': {color: '#fcd5b4'}
    };
    var gridRowNum = 4,
        gridColNum = 1,
        envDict = {
            'LP11': {
                graphData: [{
                    x: 240,
                    y: 871,
                    width: 75,
                    height: 60
                }, {
                    x: 240,
                    y: 453,
                    width: 75,
                    attr: {
                        'text-anchor': 'middle'
                    }
                }, {
                    x: 240,
                    y: 485,
                    width: 75,
                    attr: {
                        fill: '#f00',
                        'text-anchor': 'middle'
                    }
                }]
            },
            'LP12': {
                graphData: [{
                    x: 240,
                    y: 749,
                    width: 75,
                    height: 60
                }, {
                    x: 240,
                    y: 575,
                    width: 75,
                    attr: {
                        'text-anchor': 'middle'
                    }
                }, {
                    x: 240,
                    y: 607,
                    width: 75,
                    attr: {
                        fill: '#f00',
                        'text-anchor': 'middle'
                    }
                }]
            },
            'LP13': {
                graphData: [{
                    x: 240,
                    y: 611,
                    width: 75,
                    height: 60
                }, {
                    x: 240,
                    y: 714,
                    width: 75,
                    attr: {
                        'text-anchor': 'middle'
                    }
                }, {
                    x: 240,
                    y: 746,
                    width: 75,
                    attr: {
                        fill: '#f00',
                        'text-anchor': 'middle'
                    }
                }]
            },
            'LP14': {
                graphData: [{
                    x: 240,
                    y: 488,
                    width: 75,
                    height: 60
                }, {
                    x: 240,
                    y: 835,
                    width: 75,
                    attr: {
                        'text-anchor': 'middle'
                    }
                }, {
                    x: 240,
                    y: 867,
                    width: 75,
                    attr: {
                        fill: '#f00',
                        'text-anchor': 'middle'
                    }
                }]
            },
            'LP15': {
                graphData: [{
                    x: 240,
                    y: 350,
                    width: 75,
                    height: 60
                }, {
                    x: 240,
                    y: 973,
                    width: 75,
                    attr: {
                        'text-anchor': 'middle'
                    }
                }, {
                    x: 240,
                    y: 1005,
                    width: 75,
                    attr: {
                        fill: '#f00',
                        'text-anchor': 'middle'
                    }
                }]
            },
            'LP16': {
                graphData: [{
                    x: 240,
                    y: 228,
                    width: 75,
                    height: 60
                }, {
                    x: 240,
                    y: 1095,
                    width: 75,
                    attr: {
                        'text-anchor': 'middle'
                    }
                }, {
                    x: 240,
                    y: 1127,
                    width: 75,
                    attr: {
                        fill: '#f00',
                        'text-anchor': 'middle'
                    }
                }]
            },
            'LP21': {
                graphData: [{
                    x: 700,
                    y: 871,
                    width: 75,
                    height: 60
                }, {
                    x: 700,
                    y: 453,
                    width: 75,
                    attr: {
                        'text-anchor': 'middle'
                    }
                }, {
                    x: 700,
                    y: 485,
                    width: 75,
                    attr: {
                        fill: '#f00',
                        'text-anchor': 'middle'
                    }
                }]
            },
            'LP22': {
                graphData: [{
                    x: 700,
                    y: 749,
                    width: 75,
                    height: 60
                }, {
                    x: 700,
                    y: 575,
                    width: 75,
                    attr: {
                        'text-anchor': 'middle'
                    }
                }, {
                    x: 700,
                    y: 607,
                    width: 75,
                    attr: {
                        fill: '#f00',
                        'text-anchor': 'middle'
                    }
                }]
            },
            'LP23': {
                graphData: [{
                    x: 700,
                    y: 611,
                    width: 75,
                    height: 60
                }, {
                    x: 700,
                    y: 714,
                    width: 75,
                    attr: {
                        'text-anchor': 'middle'
                    }
                }, {
                    x: 700,
                    y: 746,
                    width: 75,
                    attr: {
                        fill: '#f00',
                        'text-anchor': 'middle'
                    }
                }]
            },
            'LP24': {
                graphData: [{
                    x: 700,
                    y: 488,
                    width: 75,
                    height: 60
                }, {
                    x: 700,
                    y: 835,
                    width: 75,
                    attr: {
                        'text-anchor': 'middle'
                    }
                }, {
                    x: 700,
                    y: 867,
                    width: 75,
                    attr: {
                        fill: '#f00',
                        'text-anchor': 'middle'
                    }
                }]
            },
            'LP25': {
                graphData: [{
                    x: 700,
                    y: 350,
                    width: 75,
                    height: 60
                }, {
                    x: 700,
                    y: 973,
                    width: 75,
                    attr: {
                        'text-anchor': 'middle'
                    }
                }, {
                    x: 700,
                    y: 1005,
                    width: 75,
                    attr: {
                        fill: '#f00',
                        'text-anchor': 'middle'
                    }
                }]
            },
            'LP26': {
                graphData: [{
                    x: 700,
                    y: 228,
                    width: 75,
                    height: 60
                }, {
                    x: 700,
                    y: 1095,
                    width: 75,
                    attr: {
                        'text-anchor': 'middle'
                    }
                }, {
                    x: 700,
                    y: 1127,
                    width: 75,
                    attr: {
                        fill: '#f00',
                        'text-anchor': 'middle'
                    }
                }]
            },
            'LP31': {
                graphData: [{
                    x: 1157,
                    y: 438,
                    width: 75,
                    height: 60
                }, {
                    x: 1157,
                    y: 453,
                    width: 75,
                    attr: {
                        'text-anchor': 'middle'
                    }
                }, {
                    x: 1157,
                    y: 485,
                    width: 75,
                    attr: {
                        fill: '#f00',
                        'text-anchor': 'middle'
                    }
                }]
            },
            'LP32': {
                graphData: [{
                    x: 1157,
                    y: 560,
                    width: 75,
                    height: 60
                }, {
                    x: 1157,
                    y: 575,
                    width: 75,
                    attr: {
                        'text-anchor': 'middle'
                    }
                }, {
                    x: 1157,
                    y: 607,
                    width: 75,
                    attr: {
                        fill: '#f00',
                        'text-anchor': 'middle'
                    }
                }]
            },
            'LP33': {
                graphData: [{
                    x: 1157,
                    y: 699,
                    width: 75,
                    height: 60
                }, {
                    x: 1157,
                    y: 714,
                    width: 75,
                    attr: {
                        'text-anchor': 'middle'
                    }
                }, {
                    x: 1157,
                    y: 746,
                    width: 75,
                    attr: {
                        fill: '#f00',
                        'text-anchor': 'middle'
                    }
                }]
            }
        };
    var product_dict = {
        'B38A TR1': '8666898', 'B48A TR1': '8667034', 'B48B TR1': '8667036', 'B38A TR0': '8615214',
        'B38B TR0': '8615218', 'B48A TR0': '8616102', 'B48B TR0': '8616126'
    };
    var calcTotalVal = function (apiData) {
        todayTotalVal = 0;
        todayPlanedVal = 0;
        $.each(apiData, function (i, o) {
            if (typeof o === 'object') {
                todayTotalVal = (todayTotalVal || 0) + parseInt(o[1]['today']);
                todayPlanedVal = (todayPlanedVal || 0) + parseInt(o[3]['today']);
            }
        });
    };

    var redrawGridDynamicContent = function (apiData, shiftNum) {
        var casting_list = ['B38A', 'B38B', 'B48A', 'B48B'],
            type_list = ['shift_1', 'shift_2', 'shift_3', 'today', 'current_week'],
            len = type_list.length,
            currentShiftColor = '#666';
        calcTotalVal(apiData);
        drawLineRate(true);
        $.each(casting_list, function (i, v) {
            var idx = i + '0';
            var svgTable = svgTableDict[idx];
            var rd = apiData[v],
                n = 0;
            for (n; n < len; n++) {
                var tName = type_list[n];
                if (rd[1][tName] > 0 && rd[1][tName] < rd[3][tName]) {
                    var text = rd[1][tName];
                    rd[1][tName] = {
                        fill: '#f00',
                        text: text
                    }
                }
                else {
                    var text = rd[1][tName];
                    rd[1][tName] = {
                        fill: '#0f0',
                        text: text
                    }
                }
                if (rd[2][tName] > 0 && rd[2][tName] < rd[0][tName]) {
                    var text = rd[2][tName];
                    rd[2][tName] = {
                        fill: '#f00',
                        text: text
                    }
                } else {
                    var text = rd[2][tName];
                    rd[2][tName] = {
                        fill: '#0f0',
                        text: text
                    }
                }

                if (rd[4][tName] < 0) {
                    var text = rd[4][tName];
                    rd[4][tName] = {
                        fill: '#f00',
                        text: text
                    }
                } else {
                    var text = rd[4][tName];
                    rd[4][tName] = {
                        fill: '#0f0',
                        text: text
                    }
                }
            }
            if (shiftNum) {
                var sn = 1;
                for (sn; sn <= 3; sn++) {
                    var bgColor = '#000';
                    if (sn == shiftNum) {
                        bgColor = currentShiftColor;
                    }
                    svgTable.drawHeaderCell({bgColor: bgColor}, sn);
                    var tName = type_list[sn - 1];
                    rd[0][tName] = $.isPlainObject(rd[0][tName]) ? $.extend({bgColor: bgColor}, rd[0][tName]) : {
                        bgColor: bgColor,
                        text: rd[0][tName]
                    };
                    rd[1][tName] = $.isPlainObject(rd[1][tName]) ? $.extend({bgColor: bgColor}, rd[1][tName]) : {
                        bgColor: bgColor,
                        text: rd[1][tName]
                    };
                    rd[2][tName] = $.isPlainObject(rd[2][tName]) ? $.extend({bgColor: bgColor}, rd[2][tName]) : {
                        bgColor: bgColor,
                        text: rd[2][tName]
                    };
                    rd[3][tName] = $.isPlainObject(rd[3][tName]) ? $.extend({bgColor: bgColor}, rd[3][tName]) : {
                        bgColor: bgColor,
                        text: rd[3][tName]
                    };
                    rd[4][tName] = $.isPlainObject(rd[4][tName]) ? $.extend({bgColor: bgColor}, rd[4][tName]) : {
                        bgColor: bgColor,
                        text: rd[4][tName]
                    };
                }
            }
            svgTable.setRowData(rd);
            svgTable.draw(true);
        })
    };

    // 一些不需要经常改变的图形
    var drawLazyGraph = function () {
        // 温度不需要显示
//            $.each(graphInfoList, function (k, v) {
//                drawInfoLayer(v);
//            });
        $.each(envDict, function (k, v) {
            if (v && v['graphData']) {
                var arr = v['graphData'];
                if (arr && arr.length == 3) {
                    arr[0]['color'] = v.color;
                    arr[0]['product'] = v.product;
                    arr[0]['rtn'] = product_dict[v.product];
                    arr[0]['tool_num'] = v.tool_num;
                    arr[1]['text'] = v['total'] || 0;
                    arr[2]['text'] = v['damage'] || 0;
                    drawInfoLayer(arr);
                }
            }
        });
    };

    var drawCutline = function () {
        var tpl = '<div class="com-box"><div class="com-left"><div class="text-center com-title">Production Type</div><div class="com-left-bottom"><div class="text-center com-status"><p>Machine Status</p></div><div class="com-left-part2"><div class="com-ok text-center">Current day OK parts</div><div class="com-tasa text-center">Current day TASA parts</div></div></div></div><div class="com-right"><div class="com-reset text-center">Reset</div><div class="com-num text-center">Tool number</div><div class="com-counter text-center">Counter</div></div></div>';
        var xFix = 838,
            yFix = 860;
        if (isFullScreen) {
            xFix = 890;
            yFix = 900;
        }
        var x = calcScaleSize(legendWt + xFix),
            y = calcScaleSize(yFix + midObj.titleBarHt);
        var styles = {
            top: y + 'px',
            left: x + 'px',
            transform: 'scale(' + midObj.imgZoomScale + ')'
        };
        var $box = $(tpl).css(styles);
        $stageLayer.append($box);
    };

    var $progressStrip = $('#progressStrip'),
        progressStripWt = $progressStrip.width(),
        $pBar = $progressStrip.find('.bar'),
        incWt = parseInt((1000 / (loopTimeSpan - 1000)) * progressStripWt * 100) / 100; // 增长百分比

    var initEnvData = function () {
        clearInterval(progressTimeHandle);
        $pBar.removeClass('linear-increase').css('width', '0');
        progressTimeHandle = setInterval(function () {
            if ($pBar.hasClass('linear-increase') === false) {
                $pBar.addClass('linear-increase')
            }
            var curProBarWt = parseInt($pBar.width()),
                newProBarWt = incWt + curProBarWt + 'px';
            $pBar.css('width', newProBarWt);
        }, 1000);
        $.ajax({
            url: '/NEP/ALS/api/environment_data?v=1.2&timestamp=' + Date.now(),
            dataType: 'json',
            success: function (resp) {
                if (resp) {
                    if (resp.data) {
                        var lpState = resp['lp_state'];
                        var toolNumDict = resp['tool_num'];
                        var midSto = {};
                        toolCounterDict = resp['counter'];
                        $.each(resp.data, function (idx, o) {
                            var akz = o['akz'];
                            if (envDict[akz] != undefined) {
                                if (midSto[akz] === undefined) {
                                    midSto[akz] = {}
                                }
                                var tmpObj = midSto[akz];
                                if (tmpObj['total'] === undefined) {
                                    tmpObj['total'] = 0;
                                }
                                if (tmpObj['damage'] === undefined) {
                                    tmpObj['damage'] = 0;
                                }
                                tmpObj['total'] += parseInt(o['cnt']);
                                if (o['statusid'] != 1) {
                                    tmpObj['damage'] = parseInt(o['cnt']);
                                }
                            }
                        });

                        $.each(envDict, function (k, v) {
                            v['total'] = (midSto[k] && midSto[k]['total']) ? midSto[k]['total'] : 0;
                            v['damage'] = (midSto[k] && midSto[k]['damage']) ? midSto[k]['damage'] : 0;
                            if (lpState[k]) {
                                var ste = lpState[k]['state'].toLocaleLowerCase();
                                v['state'] = ste;
                                v['product'] = lpState[k]['product'];
                                if (legDict[ste]) {
                                    v['color'] = legDict[ste]['color'];
                                }
                            }
                            if (toolNumDict && toolNumDict[k]) {
                                v['tool_num'] = toolNumDict[k];
                            }
                        });
                        drawLazyGraph();
                    }
                    if (resp['api_data']) {
                        redrawGridDynamicContent(resp['api_data'], resp['shift_num']);
                    }
                }
            }
        });
    };

    var getImgSize = function (url, callFn) {
        $('<img/>').attr('src', url).load(function () {
            callFn.call(this);
        });
    };

    var initLayout = function () {
        paper = Raphael('stage', winWt, winHt);
        $stageLayer.css({
            height: winHt
        });
        getImgSize(pImg, function () {
            var img = this;
            var imgWt = midObj.imgWt = img.width,
                imgHt = midObj.imgHt = img.height;
            var scaleImgHt = midObj.scaleImgHt = winHt - titleBarHt,
                imgWHScale = midObj.imgWHScale = imgWt / imgHt,
                scaleImgWt = midObj.scaleImgWt = parseInt(scaleImgHt * imgWHScale);
            midObj.imgObj = paper.image(pImg, legendWt, titleBarHt, scaleImgWt, scaleImgHt);
            drawTitle();
            calcBoardSize();
            drawLegend();
            drawCutline();
        });
    };

    var calcBoardSize = function () {
        midObj.boardXAxis = midObj.scaleImgWt + legendWt; // board 起始x坐标
        midObj.boardYAxis = midObj.titleBarHt; // board 起始y坐标

        midObj.lineRateHt = 60;

        midObj.boardWt = winWt - midObj.boardXAxis;
        midObj.boardHt = winHt - midObj.titleBarHt - midObj.lineRateHt;

        midObj.boardGrid = [];
        midObj.boardGapWt = calcScaleSize(12);
        midObj.boardGapHt = calcScaleSize(12);
        midObj.boardGridItemWt = (midObj.boardWt - (gridColNum - 1) * midObj.boardGapWt) / gridColNum;
        midObj.boardGridItemHt = (midObj.boardHt - (gridRowNum - 1) * midObj.boardGapHt) / gridRowNum;

        for (var i = 0; i < gridRowNum; i++) {
            for (var j = 0; j < gridColNum; j++) {
                drawGrid(i, j);
            }
        }
        drawLineRate();
    };

    var drawLineRate = function (redraw) {
        if (redraw) {
            var date = new Date(),
                y = date.getFullYear(),
                m = date.getMonth() + 1,
                d = date.getDate(),
                paddingNum = function (n) {
                    if (n < 10) {
                        n = '0' + n;
                    }
                    return n;
                };
            var ds = y + '/' + paddingNum(m) + '/' + paddingNum(d) + ' 06:00:00',
                ts = (new Date(ds)).getTime() / 1000,
                nts = parseInt((new Date()).getTime() / 1000),
                nh = parseInt((nts - ts) / 360) / 10,
                rate = nh != 0 ? parseInt(todayTotalVal * 100 / nh) / 100 : 0;

            lineRateCache['text1'].attr({
                text: 'Current total today = '
            });
            var tColor = '#0f0';
            if (todayPlanedVal > todayTotalVal) {
                tColor = '#f00';
            }
            lineRateCache['text1v'].attr({
                text: todayTotalVal,
                'fill': tColor
            });
            lineRateCache['text2'].attr({
                text: '| Current line rate = ' + rate + ' U/H'
            });
        }
        else {
            var x = midObj.boardXAxis + midObj.boardGapWt,
                y = midObj.boardYAxis + 4 * (midObj.boardGridItemHt + midObj.boardGapHt),
                wt = (midObj.boardWt - midObj.boardGapWt),
                ht = midObj.lineRateHt - midObj.boardGapHt;
            paper.rect(x, y, wt, ht).attr({fill: '#000', 'stroke-width': 0, 'stroke': '#000'});
            var attrObject = {
                'text-anchor': 'start',
                'font-size': 20,
                'font-weight': 900,
                'fill': '#0f0'
            };
            var tx = x + 12,
                ty = y + 24;
            lineRateCache['text1'] = paper.text(tx, ty, 'Current total today =').attr(attrObject);
            var t1Handle = lineRateCache['text1'].getBBox();
            tx += t1Handle.width + 12;
            lineRateCache['text1v'] = paper.text(tx, ty, '--').attr(attrObject);
            tx += 50;
            lineRateCache['text2'] = paper.text(tx, ty, '| Current line rate = --').attr(attrObject);
        }
    };

    var drawGrid = function (rn, cn) {
        var gx = midObj.boardXAxis + cn * midObj.boardGridItemWt + midObj.boardGapWt,
            gy = midObj.boardYAxis + rn * (midObj.boardGridItemHt + midObj.boardGapHt),
            castingList = ['B38A', 'B38B', 'B48A', 'B48B'];
        var ops = {
            x: gx,
            y: gy,
            width: midObj.boardGridItemWt,
            height: midObj.boardGridItemHt,
            r: 0,
            bgColor: '#000',
            rowNum: 6,
            colNum: 6,
            columns: [
                {"data": "casting_name", "text": castingList[rn], "align": "end", bgColor: '#000', 'fontSize': tableStrFontsize},
                {"data": "shift_1", "text": "Shift 1", "align": "middle", bgColor: '#000', 'fontSize': tableStrFontsize},
                {"data": "shift_2", "text": "Shift 2", "align": "middle", bgColor: '#000', 'fontSize': tableStrFontsize},
                {"data": "shift_3", "text": "Shift 3", "align": "middle", bgColor: '#000', 'fontSize': tableStrFontsize},
                {"data": "today", "text": "Today", "align": "middle", bgColor: '#000', 'fontSize': tableStrFontsize},
                {"data": "current_week", "text": "Current Week", "align": "middle", bgColor: '#000', width: 125, 'fontSize': tableStrFontsizeSmall}
            ]
        };
        var idx = rn + '' + cn;
        var svgTable = new SVGTable(ops, paper);
        svgTableDict[idx] = svgTable;
        svgTable.setRowData([
            {
                "casting_name": {text: 'Target', 'fontSize': tableStrFontsize},
                "shift_1": {text: '-', 'fontSize': tableFontsize},
                "shift_2": {text: '-', 'fontSize': tableFontsize},
                "shift_3": {text: '-', 'fontSize': tableFontsize},
                "today": {text: '-', 'fontSize': tableFontsize},
                "current_week": {text: '-', 'fontSize': tableFontsize}
            },
            {
                "casting_name": {text: 'Current', 'fontSize': tableStrFontsize},
                "shift_1": {text: '-', 'fontSize': tableFontsize},
                "shift_2": {text: '-', 'fontSize': tableFontsize},
                "shift_3": {text: '-', 'fontSize': tableFontsize},
                "today": {text: '-', 'fontSize': tableFontsize},
                "current_week": {text: '-', 'fontSize': tableFontsize}
            },
            {
                "casting_name": {text: 'Forecast', 'fontSize': tableStrFontsize},
                "shift_1": {text: '-', 'fontSize': tableFontsize},
                "shift_2": {text: '-', 'fontSize': tableFontsize},
                "shift_3": {text: '-', 'fontSize': tableFontsize},
                "today": {text: '-', 'fontSize': tableFontsize},
                "current_week": {text: '-', 'fontSize': tableFontsize}
            },
            {
                "casting_name": {text: 'Planned', 'fontSize': tableStrFontsize},
                "shift_1": {text: '-', 'fontSize': tableFontsize},
                "shift_2": {text: '-', 'fontSize': tableFontsize},
                "shift_3": {text: '-', 'fontSize': tableFontsize},
                "today": {text: '-', 'fontSize': tableFontsize},
                "current_week": {text: '-', 'fontSize': tableFontsize}
            },
            {
                "casting_name": {text: 'Deviation', 'fontSize': tableStrFontsize},
                "shift_1": {text: '-', 'fontSize': tableFontsize},
                "shift_2": {text: '-', 'fontSize': tableFontsize},
                "shift_3": {text: '-', 'fontSize': tableFontsize},
                "today": {text: '-', 'fontSize': tableFontsize},
                "current_week": {text: '-', 'fontSize': tableFontsize}
            }
        ]);
        svgTable.draw();
    };

    var drawTitle = function () {
        var span1Wt = 440,
            span2Wt = 450,
            span3Wt = 361,
            titRectWt = 80,
            titRectHt = 32,
            shortAreaHt = 836;
        var textY = midObj.titleBarHt + titRectHt * 0.5;
        midObj.imgZoomScale = midObj.scaleImgWt / midObj.imgWt;
        var text1X = calcScaleSize(span1Wt),
            text2X = calcScaleSize(span2Wt),
            text3X = calcScaleSize(span3Wt),
            sShortAreaHt = calcScaleSize(shortAreaHt),
            strokeWith = calcScaleSize(30),
            halfStrokeWith = 0.5 * strokeWith,
            sPicHt = midObj.scaleImgHt + halfStrokeWith;

        var line1RectColor = 'transparent',
            line2RectColor = 'transparent',
            line3RectColor = 'transparent',
            frameYAxis = titleBarHt - strokeWith;
        if(lineNum === '1') {
            line1RectColor = '#0070c0';
            paper.rect(legendWt + halfStrokeWith, frameYAxis, text1X - strokeWith, sPicHt).attr({
                fill: 'transparent',
                stroke: line1RectColor
            }).attr({'stroke-width': strokeWith});
        }
        else if(lineNum === '2') {
            line2RectColor = '#0070c0';
            paper.rect(legendWt + text1X + halfStrokeWith, frameYAxis, text2X - strokeWith, sPicHt).attr({
                fill: 'transparent',
                stroke: line2RectColor
            }).attr({'stroke-width': strokeWith});
        }
        else if(lineNum === '3') {
            line3RectColor = '#0070c0';
            paper.rect(legendWt + text1X + text2X + halfStrokeWith, frameYAxis, text3X - strokeWith, sShortAreaHt).attr({
                fill: 'transparent',
                stroke: line3RectColor
            }).attr({'stroke-width': strokeWith});
        }
        var titBar = paper.rect(0, 0, winWt, midObj.titleBarHt);
        titBar.attr({
            'fill': '#0070c0',
            'stroke-width': 0
        });
        paper.text(12, 15, 'Foundry Casting Area').attr({
            'text-anchor': 'start',
            'font-size': 20,
            'font-weight': 900,
            'fill': '#fff'
        });

        paper.rect((text1X - titRectWt) * 0.5 + legendWt, midObj.titleBarHt, titRectWt, titRectHt).attr({
            fill: line1RectColor,
            stroke: line1RectColor
        });

        paper.rect(text1X + (text2X - titRectWt) * 0.5 + legendWt, midObj.titleBarHt, titRectWt, titRectHt).attr({
            fill: line2RectColor,
            stroke: line2RectColor
        });

        paper.rect(text1X + text2X + (text3X - titRectWt) * 0.5 + legendWt, midObj.titleBarHt, titRectWt, titRectHt).attr({
            fill: line3RectColor,
            stroke: line3RectColor
        });

        paper.text(text1X * 0.5 + legendWt, textY, 'Line 1').attr({
            'text-anchor': 'middle',
            'font-size': 20,
            'font-weight': 900,
            'fill': '#fff'
        });

        paper.text(text1X + text2X * 0.5 + legendWt, textY, 'Line 2').attr({
            'text-anchor': 'middle',
            'font-size': 20,
            'font-weight': 900,
            'fill': '#fff'
        });

        paper.text(text1X + text2X + text3X * 0.5 + legendWt, textY, 'Line 3').attr({
            'text-anchor': 'middle',
            'font-size': 20,
            'font-weight': 900,
            'fill': '#fff'
        });

        initEnvData();
        timeHandle = setInterval(function () {
            initEnvData();
        }, loopTimeSpan);
    };

    var calcScaleSize = function (val) {
        var newVal = parseInt(val * midObj.imgZoomScale * 100) / 100;
        return newVal;
    };
    // 画左侧LP11-LP33数据
    var drawInfoLayer = function (layerData) {
        var d1 = layerData[0],
            d2 = layerData[1],
            d3 = layerData[2];
        if (layerData.lock === undefined) {
            d1.x = calcScaleSize(d1.x - 80) + legendWt;
            d1.y = calcScaleSize(d1.y - 40) + midObj.titleBarHt;
            d1.width = 174;
            d1.height = 104;
            var rtn = d1.rtn;
            var wpx = d1.width + 'px';
            var hpx = d1.height + 'px';
            var styles = {
                position: 'absolute',
                top: d1.y + 'px',
                left: d1.x + 'px',
                width: wpx,
                height: hpx,
                transform: 'scale(' + midObj.imgZoomScale + ')'
            };
            var tpl = '<div class="info-box">' +
                '<div class="left-side">' +
                '<div class="info-title"></div>' +
                '<div class="fl-wrap"><div class="color-info"></div>' +
                '<div class="meta-wrap"><div class="meta-row l-row-1 __JVal1"></div><div class="meta-row l-row-2 __JVal2"></div></div></div>' +
                '</div>' +
                '<div class="right-side">' +
                '<div class="r-row-1 icon-reset __JReset">reset</div>' +
                '<div class="r-row-2 __JVal3">--</div>' +
                '<div class="r-row-3 __JVal4">--</div>' +
                '</div>' +
                '</div>';
            var $box = $(tpl).css(styles);
            // layerData['$box'] = $box;
            $box.find('.info-title').text(d1.product);

            layerData['colorHandler'] = $box.find('.color-info');
            layerData['value1Handle'] = $box.find('.__JVal1');
            layerData['value2Handle'] = $box.find('.__JVal2');
            layerData['value3Handle'] = $box.find('.__JVal3');
            layerData['value4Handle'] = $box.find('.__JVal4');
            $stageLayer.append($box);
            layerData.lock = true;

            $box.find('.__JReset').on('click', function () {
                var $this = $(this);
                var $pBox = $this.closest('.info-box');
                var tool_num = $pBox.find('.__JVal3').text();
                if (isExpired() == false) {
                    var isConfirm = confirm('Are you sure reset the ' + tool_num + ' tool number counter?');
                    var data = {
                        tool_number: tool_num,
                        rtn: rtn
                    };
                    if (isConfirm) {
                        $.ajax({
                            url: '/NEP/ALS/api/ResetFoundryFinalInspectionCounter',
                            type: 'POST',
                            data: data,
                            dataType: 'json',
                            success: function (resp) {
                                if (resp && resp['status'] == 1) {
                                    alert('It wills go into effect in 15 seconds.')
                                    // setTimeout(function() {
                                    //     window.location.reload();
                                    // }, 10000);
                                }
                                else {
                                    alert('Counter reset failed.')
                                }
                            }
                        });
                    }
                }
                else {
                    var d = dialog({
                        content: 'Insufficient permissions to perform this action.'
                    });
                    d.show();
                    setTimeout(function () {
                        d.close().remove();
                    }, 6000);
                }
            });
        }
        layerData['colorHandler'].css({
            'background-color': d1.color
        });
        layerData['value1Handle'].text(d2.text);
        layerData['value2Handle'].text(d3.text);
        if (d1.tool_num !== undefined) {
            layerData['value3Handle'].text(d1.tool_num);
            // var tool_index = d1.rtn + '_' + d1.tool_num;
            var rtn = d1.rtn,
                tool_num = d1.tool_num,
                tool_index = rtn + '_' + tool_num;
            if (toolCounterDict && toolCounterDict[tool_index] >= 0) {
                layerData['value4Handle'].text(toolCounterDict[tool_index]);
            }
        }
    };

    var drawLegend = function () {
        var rx = 5,
            ry = midObj.titleBarHt,
            wt = 30,
            ht = 30,
            itemHt = 60;
        wt = calcScaleSize(wt);
        ht = calcScaleSize(ht);
        var cnt = 0;
        $.each(legDict, function (k, v) {
            var x = calcScaleSize(rx + 8),
                y = calcScaleSize(ry + cnt * itemHt + 8) + midObj.titleBarHt;
            paper.rect(x, y, wt, ht).attr({
                fill: v.color
            });
            x += wt + calcScaleSize(8);
            y += calcScaleSize(7);
            if (v.text) {
                paper.text(x, y - 3, v.text[0]).attr({
                    'text-anchor': 'start',
                    'font-size': '12',
                    'font-weight': '200'
                });
                paper.text(x, y + 10, v.text[1]).attr({
                    'text-anchor': 'start',
                    'font-size': '12',
                    'font-weight': '200'
                });
            }
            else {
                paper.text(x, y + 4, k).attr({
                    'text-anchor': 'start',
                    'font-size': '12',
                    'font-weight': '200'
                });
            }
            cnt++;
        })
    };

    var showClock = function () {
        $('#neverClock').timeTo({
            fontSize: 18,
            theme: 'black'
        });
    }
})();

var isExpired = function () {
    var auth_time = store.get('timestamp');
    var result = true;
    if (auth_time && ((Date.now() / 1000) - auth_time) < 300) {
        result = false;
    }
    return result;
};

var auth = function () {
    var code = prompt('Please input authentication code.');
    if (code == 'foundry123') {
        var nt = parseInt(Date.now() / 1000);
        store.set('timestamp', nt);
    }
};